#include "StudentManagerWidget.h"
#include "ui_StudentManagerWidget.h"

#include "UserLoginWidget.h"
#include <QMessageBox>
#include <QDateTimeEdit>
#include <QHBoxLayout>   // 水平布局
#include <QVBoxLayout>   // 垂直布局
#include <QFormLayout>   // 表单布局
#include "xinzeng.h"

#include "DbManger.h"
StudentManagerWidget::StudentManagerWidget(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::StudentManagerWidget)
{
    ui->setupUi(this);
    dbManger = DbManger::getDbPtr(); // 获取单例
    // ========== 1. 初始化表格 ==========
        ui->userTableWidget->setColumnCount(6);
        ui->userTableWidget->setHorizontalHeaderLabels({"ID", "账号", "电话", "部门", "状态", "创建时间"});
        ui->userTableWidget->horizontalHeader()->setStretchLastSection(true);

        // ========== 2. 初始化部门树 ==========
        initDepartmentTree();

        // ========== 3. 绑定按钮事件 ==========
        connect(ui->pushButton_add, &QPushButton::clicked, this, &StudentManagerWidget::addClicked);
        connect(ui->pushButton_edit, &QPushButton::clicked, this, &StudentManagerWidget::on_pushButton_edit_clicked);
        connect(ui->pushButton_delete, &QPushButton::clicked, this, &StudentManagerWidget::on_pushButton_delete_clicked);
        connect(ui->pushButton_query, &QPushButton::clicked, this, &StudentManagerWidget::on_pushButton_query_clicked);
        connect(ui->pushButton_refresh, &QPushButton::clicked, this, &StudentManagerWidget::refreshTable);

        // ========== 4. 初始加载数据 ==========
        refreshTable();
}

// ========== 私有方法：初始化部门树 ==========
void StudentManagerWidget::initDepartmentTree() {
    ui->departmentTreeWidget->clear();
    QVector<QMap<QString, QVariant>> depts = DbManger::getDbPtr()->queryDepartments(); // 假设DbManger有查询部门方法

    // 递归构建树形结构（示例：人事、研发为父节点，小组1、组1为子节点）
    QMap<QString, QTreeWidgetItem*> parentItems;
    for (auto &dept : depts) {
        QString deptName = dept["name"].toString();
        QString parentName = dept["parent"].toString();

        QTreeWidgetItem *item = new QTreeWidgetItem({deptName});
        if (parentName.isEmpty()) { // 顶级部门（人事、研发）
            ui->departmentTreeWidget->addTopLevelItem(item);
        } else { // 子部门（小组1、组1）
            if (parentItems.contains(parentName)) {
                parentItems[parentName]->addChild(item);
            }
        }
        parentItems[deptName] = item;
    }
}

// ========== 私有方法：刷新表格数据 ==========
void StudentManagerWidget::refreshTable()
{
    ui->userTableWidget->setRowCount(0); // 清空表格
    QVector<QMap<QString, QVariant>> users = DbManger::getDbPtr()->queryUsers();

    for (int i = 0; i < users.size(); ++i) {
        auto &user = users[i];
        ui->userTableWidget->insertRow(i);
        ui->userTableWidget->setItem(i, 0, new QTableWidgetItem(QString::number(user["id"].toInt())));
        ui->userTableWidget->setItem(i, 1, new QTableWidgetItem(user["account"].toString()));
        ui->userTableWidget->setItem(i, 2, new QTableWidgetItem(user["phone"].toString()));
        ui->userTableWidget->setItem(i, 3, new QTableWidgetItem(user["department"].toString()));
        ui->userTableWidget->setItem(i, 4, new QTableWidgetItem(user["status"].toString()));
        ui->userTableWidget->setItem(i, 5, new QTableWidgetItem(
                                         user["startTime"].toDateTime().toString("yyyy-MM-dd HH:mm:ss")
                                     ));
    }
}
void StudentManagerWidget::on_pushButton_exit_clicked()
{
    //关闭当前窗口
    this->close();
    //显示登录窗口
    UserLoginWidget* p=new UserLoginWidget;
    p->show();
}

StudentManagerWidget::~StudentManagerWidget()
{
    delete ui;
}
//查询
void StudentManagerWidget::on_pushButton_query_clicked()
{
    QString account = ui->accountLineEdit->text().trimmed();
    QString phone = ui->phoneLineEdit->text().trimmed();

    // 使用 prepare + bindValue 避免 SQL 注入，同时兼容空值
    QSqlQuery query;
    query.prepare(R"(
                  SELECT * FROM users
                  WHERE (:account = '' OR account LIKE :accountPattern)
                  AND (:phone = '' OR phone LIKE :phonePattern)
                  )");
    query.bindValue(":account", account);
    query.bindValue(":accountPattern", QString("%%1%").arg(account)); // %account%
    query.bindValue(":phone", phone);
    query.bindValue(":phonePattern", QString("%%1%").arg(phone));     // %phone%

    if (!query.exec()) {
        qDebug() << "查询失败：" << query.lastError().text();
        return;
    }

    // 清空表格并填充查询结果（复制 refreshTable 的行填充逻辑）
    ui->userTableWidget->setRowCount(0);
    while (query.next()) {
        int row = ui->userTableWidget->rowCount();
        ui->userTableWidget->insertRow(row);
        ui->userTableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(query.value("id").toInt())));
        ui->userTableWidget->setItem(row, 1, new QTableWidgetItem(query.value("account").toString()));
        ui->userTableWidget->setItem(row, 2, new QTableWidgetItem(query.value("phone").toString()));
        ui->userTableWidget->setItem(row, 3, new QTableWidgetItem(query.value("department").toString()));
        ui->userTableWidget->setItem(row, 4, new QTableWidgetItem(query.value("status").toString()));
        ui->userTableWidget->setItem(row, 5, new QTableWidgetItem(
                                         query.value("startTime").toDateTime().toString("yyyy-MM-dd HH:mm:ss")
                                         ));
    }
}
//重置
void StudentManagerWidget::on_pushButton_reset_clicked()
{
    // 清空查询输入框
    ui->accountLineEdit->clear();
    ui->phoneLineEdit->clear();
    // 刷新表格（显示全部数据）
    refreshTable();
}
//新增
void StudentManagerWidget::addClicked()
{
    xinzeng dialog(this); // 假设XinzengDialog是新增/编辑对话框
    if (dialog.exec() == QDialog::Accepted)
    {
        QMap<QString, QVariant> userData = dialog.getUserData(); // 从对话框获取数据
        if (DbManger::getDbPtr()->insertUser(userData)) {
            QMessageBox::information(this, "提示", "新增成功！");
            refreshTable();
        } else {
            QMessageBox::critical(this, "错误", "新增失败！");
        }
    }
}
//编辑
void StudentManagerWidget::on_pushButton_edit_clicked()
{
    QList<QTableWidgetItem*> selected = ui->userTableWidget->selectedItems();
    if (selected.isEmpty())
    {
        QMessageBox::warning(this, "提示", "请选择要编辑的行！");
        return;
    }
    int row = selected.first()->row();
    int userId = ui->userTableWidget->item(row, 0)->text().toInt();

    xinzeng dialog(this);
    dialog.setUserData(DbManger::getDbPtr()->getUserById(userId)); // 加载已有数据
    if (dialog.exec() == QDialog::Accepted)
    {
        QMap<QString, QVariant> userData = dialog.getUserData();
        if (DbManger::getDbPtr()->updateUser(userId, userData))
        {
            QMessageBox::information(this, "提示", "编辑成功！");
            refreshTable();
        } else {
            QMessageBox::critical(this, "错误", "编辑失败！");
        }
    }

}
//删除
void StudentManagerWidget::on_pushButton_delete_clicked()
{
    QList<QTableWidgetItem*> selected = ui->userTableWidget->selectedItems();
    if (selected.isEmpty())
    {
        QMessageBox::warning(this, "提示", "请选择要删除的行！");
        return;
    }
    int row = selected.first()->row();
    int userId = ui->userTableWidget->item(row, 0)->text().toInt();

    if (QMessageBox::question(this, "确认", "确定删除该用户？") == QMessageBox::Yes)
    {
        if (DbManger::getDbPtr()->deleteUser(userId))
        {
            QMessageBox::information(this, "提示", "删除成功！");
            ui->userTableWidget->removeRow(row); // 实时移除行
        }
        else
        {
            QMessageBox::critical(this, "错误", "删除失败！");
        }
    }
}
//刷新
void StudentManagerWidget::on_pushButton_refresh_clicked()
{
    // 清空表格现有数据
    ui->userTableWidget->clearContents();
    ui->userTableWidget->setRowCount(0);

    // 执行查询
    QSqlQuery sql("SELECT * FROM user");
    if (!sql.exec()) {
        qDebug() << "查询失败：" << sql.lastError().text();
        return;
    }

    int row = 0;
    while (sql.next()) {
        // 插入新行
        ui->userTableWidget->insertRow(row);

        // 获取数据
        int id = sql.value("id").toInt();
        QString zh = sql.value("zh").toString();
        int phone = sql.value("phone").toInt();
        QString bumen = sql.value("bumen").toString();
        QString zhuangtai = sql.value("zhuangtai").toString();
        QString time = sql.value("time").toString();

        // 创建表格项
        QTableWidgetItem *idItem = new QTableWidgetItem(QString::number(id));
        QTableWidgetItem *zhItem = new QTableWidgetItem(zh);
        QTableWidgetItem *phoneItem = new QTableWidgetItem(QString::number(phone));
        QTableWidgetItem *bumenItem = new QTableWidgetItem(bumen);
        QTableWidgetItem *zhuangtaiItem = new QTableWidgetItem(zhuangtai);
        QTableWidgetItem *timeItem = new QTableWidgetItem(time);

        // 设置表格项
        ui->userTableWidget->setItem(row, 0, idItem);
        ui->userTableWidget->setItem(row, 1, zhItem);
        ui->userTableWidget->setItem(row, 2, phoneItem);
        ui->userTableWidget->setItem(row, 3, bumenItem);
        ui->userTableWidget->setItem(row, 4, zhuangtaiItem);
        ui->userTableWidget->setItem(row, 5, timeItem);

        row++; // 移动到下一行
    }

    // 自动调整列宽
    //ui->tableWidget->resizeColumnsToContents();

}
//系统设置
void StudentManagerWidget::on_pushButton_systemSetting_clicked()
{

}
//警情查询
void StudentManagerWidget::on_pushButton_alarmQuery_clicked()
{

}
//调试帮助
void StudentManagerWidget::on_pushButton_testHelp_clicked()
{

}
